package modele;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * look for all the plugins in the parameter file
 * @author morhib & morhib
 *
 */
public class PluginFinder implements ActionListener {

	private static final int refreshIntervalMS=1000;
	protected final File directory;
	protected final List<PluginEventlistener> listener=new ArrayList();
	protected final ConfigurableTimer timer;
	protected Set<File> knownFiles = new HashSet();
	protected PluginFilter filter = new PluginFilter();
	
	public PluginFinder(File dir){
		super();
		this.directory=dir;
		this.timer=new ConfigurableTimer(this);
	}
	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		Set<File> currentFiles=listFiles();
		Set<File> newFiles=new HashSet<File>(currentFiles);
		newFiles.removeAll(knownFiles);
		System.out.println(currentFiles+" _ "+newFiles);
		for(File file : newFiles)
			notifyListener(file);
		
		knownFiles = currentFiles;
	}
	
	public Set<File> listFiles(){
		return new HashSet<File> (Arrays.asList(directory.listFiles(filter)));
	}
	
	public void notifyListener(File file){
		ArrayList<PluginEventlistener> listenerCopy;
		listenerCopy=new ArrayList<PluginEventlistener>(listener);
		for(PluginEventlistener listener : listenerCopy)
			listener.pluginAdded(new PluginAddedEvent(file));	
	}
	
	public void start(){
		timer.start(refreshIntervalMS);
	}

	public synchronized void addlistener(PluginEventlistener l){
		listener.add(l);
	}
}